import { ref, toRefs } from 'vue';
import * as DictDataApi from '@/api/system/dict/data';

// 数据启用状态 字典类型
export const SYS_DATA_ENABLE_STATUS = 'sys_data_enable_status';
export const SYS_DATA_PRESET_STATUS = 'sys_data_preset_status';
export const SYS_DATA_HIDDEN_STATUS = 'sys_data_hidden_status';


// export function getDictData(type: string) {
//   let strDictData = sessionStorage.getItem(type);
//   if (strDictData) {
//     return JSON.parse(strDictData);
//   }
//   const res = ref([]);
//   return (() => {
//     DictDataApi.searchByDictType(type).then((response) => {
//       const data = JSON.stringify(response.data);
//       sessionStorage.setItem(type, data);
//       res.value = response.data;
//     });
//     return res.value;
//   })();
// }


export function getDictData(type: string): Promise<any[]> {
  // 1. 先检查缓存
  let strDictData = sessionStorage.getItem(type);
  if (strDictData) {
    return Promise.resolve(JSON.parse(strDictData)); // 缓存命中，返回 resolved Promise
  }

  // 2. 缓存未命中，发起请求
  return DictDataApi.searchByDictType(type)
    .then((response) => {
      const data = response.data || [];
      // 存入缓存
      sessionStorage.setItem(type, JSON.stringify(data));
      return data;
    })
    .catch((error) => {
      console.error(`Failed to fetch dict data for type ${type}:`, error);
      throw error;
    });
}
